﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;


namespace demo.Common
{
    public static class TokenHelper
    {
        /// <summary>
        /// 当前token操作标识名
        /// </summary>
        private const string _CurrentTokenKey = "__USERTOKEN-";

        /// <summary>
        /// 客户端提交/输出的token参数名
        /// </summary>
        private const string ClientTokenName = "token";

        /// <summary>
        /// 创建防止Cookies或Session信息篡改的Token
        /// </summary>
        /// <param name="userKey">用户标识</param>
        /// <param name="areas">区域</param>
        public static void CreateToken(string userKey, string areas = "Default")
        {
            areas = areas.ToUpper();
            Cookie.setCookie(_CurrentTokenKey + areas, System.Guid.NewGuid().ToString(), 30);
        }

        /// <summary>
        /// 说明：防止Cookies或Session信息篡改Token
        /// </summary>
        /// <param name="helper">HtmlHelper类（扩展方法对象）</param>
        /// <param name="areas">从指定区域从输出</param>
        /// <returns>输出一个带Token的input type="hidden"的标签</returns>
        public static MvcHtmlString AntiToken(this HtmlHelper helper, string areas = "Default")
        {
            string tokenValue = "";
            areas = areas.ToUpper();
            tokenValue = Cookie.getCookie(_CurrentTokenKey + areas);
            return new MvcHtmlString(string.Format("<input type=\"hidden\" id=\"{0}\" name=\"{0}\" value=\"{1}\"  />", ClientTokenName, tokenValue));
        }

        /// <summary>
        /// 校验篡改Token是否被篡改
        /// </summary>
        /// <param name="areas">指定区域</param>
        /// <returns>校验是否成功</returns>
        public static bool VerifyToken(string areas = "Default")
        {
            areas = areas.ToUpper();
            if (HttpContext.Current.Request[ClientTokenName] == null) return false;
            return Cookie.getCookie(_CurrentTokenKey + areas) == HttpContext.Current.Request[ClientTokenName].ToString(CultureInfo.InvariantCulture);
        }

        /// <summary>
        /// 清空Token
        /// </summary>
        /// <param name="areas">指定区域</param>
        public static void ClearToken(string areas = "Default")
        {
            areas = areas.ToUpper();
            Cookie.delCookie(_CurrentTokenKey + areas);
        }

        /// <summary>
        /// 获得Token
        /// </summary>
        /// <param name="areas">指定区域</param>
        /// <returns>Token字符串</returns>
        public static string GetToken(string areas = "Default")
        {
            areas = areas.ToUpper();
            return Cookie.getCookie(_CurrentTokenKey + areas);
        }
    }

    [Serializable]
    public class Token
    {
        public string UserKey { get; set; }

        public string TokenValue { get; set; }

        public string Area { get; set; }
    }
}
